﻿using Commons.Helpers;
using Commons.Responses;
using System.Net;
using System.Text.Json;

namespace WebAPI.Helpers
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<GlobalExceptionMiddleware> _logger;

        public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);  // 执行下一个中间件
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex, "A repository exception occurred.");
                await HandleExceptionAsync(context, ex);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An unhandled exception occurred.");
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            // 根据不同异常类型返回不同的消息
            //var result = JsonSerializer.Serialize(new
            //{
            //    error = exception is CustomException ? "Repository error occurred" : "An error occurred",
            //    details = exception.Message
            //});

            var result = JsonSerializer.Serialize(new MessageResponse(exception.Message, false)
                );

            return context.Response.WriteAsync(result);
        }
    }
}
